#!/bin/bash
# Starts the helper and opens the page. If an instance is already listening,
# just surface it rather than failing on a port collision.
set -uo pipefail
RES="$(cd "$(dirname "${BASH_SOURCE[0]}")/../Resources" && pwd)"
URL="http://localhost:1931"

if curl -sf --max-time 2 "$URL/health" >/dev/null 2>&1; then
  open "$URL"; exit 0
fi

# HOME can be unset when launched from Finder in odd states; helper.mjs writes
# its schedules under Application Support and needs a real one.
: "${HOME:=$(/usr/bin/dscl . -read "/Users/$(id -un)" NFSHomeDirectory | awk '{print $2}')}"
export HOME

"$RES/node" "$RES/helper.mjs" &
HELPER=$!
trap 'kill "$HELPER" 2>/dev/null' EXIT INT TERM

for _ in $(seq 1 40); do
  curl -sf --max-time 1 "$URL/health" >/dev/null 2>&1 && break
  kill -0 "$HELPER" 2>/dev/null || break
  sleep 0.25
done
open "$URL"
wait "$HELPER"
